package cn.edu.ujn.lab3.controller;


import cn.edu.ujn.lab3.entity.Page;
import cn.edu.ujn.lab3.entity.user;
import cn.edu.ujn.lab3.entity.userDTO;
import cn.edu.ujn.lab3.service.IUserService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;

@Controller
public class userController {

    @Autowired
    private IUserService userService;

    @RequestMapping("/index")
    public String ToIndex() {
        return "index";
    }
    @GetMapping("/login")
    public String ToLogIn() {
        return "login";
    }
    @PostMapping("/logout")
    public String ToLogOut(HttpSession session) {
        session.removeAttribute("user");
        return "login";
    }
    @PostMapping("/login")
    public String login(@Param("code")String code, @Param("password")String password, HttpSession session) {
        if(userService.login(code,password,session)){return "index";}
        return "login";
    }

    @PostMapping("/page")
    @ResponseBody
    public List<userDTO> findPage(@RequestBody Page page){
        return userService.selectUserByPage(page);
    }
    @PostMapping("/selectByName")
    @ResponseBody
    public List<user> selectByName(@RequestBody HashMap<String, String> map){
        String name = map.get("name");
        return userService.selectByName(name);
    }
    @PostMapping("/selectAll")
    @ResponseBody
    public List<user> selectAll(){
        return userService.selectAll();
    }

    @PostMapping("/add")
    @ResponseBody
    public Boolean addUser(@RequestBody user user){
        Boolean flag = userService.addUser(user);
        return flag;
    }
    @PostMapping("/update")
    @ResponseBody
    public Boolean updateUser(@RequestBody userDTO user){
        Boolean flag = userService.updateUser(user);
        return flag;
    }
    @PostMapping("/delete")
    @ResponseBody
    public Boolean deleteUser(@RequestBody HashMap<String, String> map){
        String id = map.get("id");
        Integer idd = Integer.parseInt(id);
        Boolean flag = userService.deleteUser(idd);
        return flag;
    }
}
